//
//  OAuthViewController.swift
//  HyWeibo
//
//  Created by HY-Mac on 16/6/30.
//  Copyright © 2016年 HY-Mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {
    

//定义一个WebView属性
    let webView = UIWebView()
    override func loadView() {
        
        view = webView
        print(view)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadOAuthPage()
        webView.delegate = self
        
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OAuthViewController.close), name: "AccountViewModelLoadUserInfo", object: nil)
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OAuthViewController.close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(OAuthViewController.fullFill))
    }
    @objc private func fullFill(){
        let jsString = "document.getElementById('userId').value = '18600653280' ,document.getElementById('passwd').value = 'qq921103'";
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    @objc private func close(){
        self.dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appid + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

}
//专门处理 webView所有的协议方法
extension OAuthViewController: UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    //协议方法 返回true 表示当前对象可以正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print(request.URL)
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        //print(urlString)
        guard let query = request.URL?.query else {
            return false
        }
        //获取回调 url 的code
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        //print(code)
        //根据code获取token信息
        AccountViewModel().loadTokenInfo(code) { (error) in
            print(error)
            print("come here")
        }
        //loadTokenInfo(code)
        return false
    }
/*    func loadTokenInfo(code: String){
        let urlString  = "https://api.weibo.com/oauth2/access_token"
        let parameter = ["client_id": appid, "client_secret": appSercet, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameter, success: { (_, result) in
            //print(result)
            if let dict = result as? [String: AnyObject]{
                //let access_token = dict["access_token"] as? String
                //let uid = dict["uid"] as? String
                let userAccount = UserAccount(dict: dict)
                //print(userAccount)
                self.loadUserInfo(userAccount)
                
            }
            
            
            
            
            
            }) { (_, error) in
                print(error)
        }
        
    }
    func loadUserInfo(userAccount: UserAccount){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameter = ["access_token": userAccount.access_token!, "uid": userAccount.uid!]
        AFN.GET(urlString, parameters: parameter, success: { (_, result) in
            //print(result)
            if let dict = result as? [String: AnyObject]{
                userAccount.avatar_large = dict["avatar_large"] as? String
                userAccount.name = dict["name"] as? String
               // userAccount.expires_in = dict["expires_in"] as? NSTimeInterval
               // print(userAccount)
                userAccount.saveUserAccount()
            }
            }) { (_, error) in
                print(error)
        }
    }*/
}

